import { ConfigEnv, defineConfig, UserConfig } from "vite";
import { resolve } from "path";
import vue from "@vitejs/plugin-vue";

// element-plus
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

// gzip压缩
import viteCompression from "vite-plugin-compression";

// 支持jsx或者tsx语法
import vueJsx from "@vitejs/plugin-vue-jsx";

// https://vitejs.dev/config/
export default defineConfig((mode: ConfigEnv): UserConfig => {
	console.log(mode);
	return {
		resolve: {
			alias: {
				"@": resolve(__dirname, "./src"),
				// 不加这个vue-i18n会报一个警告
				"vue-i18n": "vue-i18n/dist/vue-i18n.cjs.js"
			}
		},
		// global css
		css: {
			preprocessorOptions: {
				scss: {
					additionalData: `@import "@/styles/var.scss";`
				}
			}
		},
		server: {
			// 服务器主机名，如果允许外部访问，可设置为"0.0.0.0"
			host: "0.0.0.0",
			port: 9999,
			// 自动打开
			// open: true,
			// 不知道作用
			// cors: true,
			// https: false,
			// 代理跨域
			proxy: {
				// 自己的后端
				// "/api": {
				// 	target: "http://localhost:8888/",
				// 	changeOrigin: true,
				// 	rewrite: path => path.replace(/^\/api/, "")
				// }
				// 作者mock数据
				"/api": {
					target: "https://mock.mengxuegu.com/mock/629d727e6163854a32e8307e", // easymock
					changeOrigin: true,
					rewrite: path => path.replace(/^\/api/, "")
				}
			}
		},
		plugins: [
			vue(),
			vueJsx(),
			AutoImport({
				resolvers: [ElementPlusResolver()]
			}),
			Components({
				resolvers: [ElementPlusResolver()]
			}),
			viteCompression({
				verbose: true,
				disable: false,
				threshold: 10240,
				algorithm: "gzip",
				ext: ".gz"
			})
		],
		build: {
			// (不加这个会警告)现在Vite默认使用esbuild去作为代码压缩器，如果想要使用terserOptions这些配置，要增加minify：terser。看文档默认esbuild压缩有优势，那也可以删掉terserOptions
			minify: "terser",
			// 去除console和debugger
			terserOptions: {
				compress: {
					drop_console: true,
					drop_debugger: true
				}
			},
			rollupOptions: {
				output: {
					// 静态资源分类打包
					chunkFileNames: "static/js/[name]-[hash].js",
					entryFileNames: "static/js/[name]-[hash].js",
					assetFileNames: "static/[ext]/[name]-[hash].[ext]"
				}
			}
		}
	};
});
